from db import DB
from db_base import Users as DBUser
from db_base import Oplogs
# from mysql.connector.errors import IntegrityError
from sqlalchemy.exc import IntegrityError
import config


class User():
    def __init__(self, nickname, password):
        self.db = DB()
        self.nickname = nickname
        self.password = password
        self.is_online = self.sign_in()

    def _set_online(self):
        info_db = self.db.session.query(DBUser).filter(DBUser.nickname.in_([self.nickname]))
        for i in info_db:
            i.is_online = True
        self.db.session.commit()
        self._add_op_record(config.op_sign_in, True)

    def sign_in(self):
        def verify(password):
            print('{}\n{},{}'.format('*' * 80, self.password, password))
            return self.password == password

        info_db = self.db.session.query(DBUser).filter(DBUser.nickname.in_([self.nickname]))
        for i in info_db:
            if verify(i.password):
                self._set_online()
                u._add_op_record(config.op_sign_in, True)
                return True

    def sign_up(self):
        try:
            if not self.db._insert(DBUser(nickname=self.nickname, password=self.password)):
                self._add_op_record(config.op_sign_up, True)
                return True

        except IntegrityError as e:
            self._add_op_record(config.op_sign_up, False)
            return 'this nickname has used!'

    def _add_op_record(self, op, result):
        try:
            if not self.db._insert(Oplogs(nickname=self.nickname, op=op, result=result)):
                return True
        except IntegrityError as e:
            return 'insert operation fail!'

    def password_reset(self, password):
        if not self.is_online:
            return 'please sign in!'
        info_db = self.db.session.query(DBUser).filter(DBUser.nickname.in_([self.nickname]))
        for i in info_db:
            i.password = password
            try:
                self.db.session.commit()
                self._add_op_record(config.op_password_reset, True)
            except BaseException:
                self._add_op_record(config.op_password_reset, False)

    def _set_offline(self):
        info_db = self.db.session.query(DBUser).filter(DBUser.nickname.in_([self.nickname]))
        for i in info_db:
            i.is_online = False
            self.db.session.commit()
            self._add_op_record(config.op_offline, True)

    def __del__(self):
        self._set_offline()


if __name__ == '__main__':
    u = User('123', '123')
    # u.sign_up()
    u.sign_in()
